package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.ListResult;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/admin/dish")
@Api(tags = {"菜品管理接口"})
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("新增菜品")
    public Result addDish(@RequestBody DishDTO dishDTO){
        log.info("添加菜品{}",dishDTO);
        //清理缓存数据
        cleanAllCache();
        dishService.addDish(dishDTO);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("分页查询")
    public Result<PageResult> pageQuery(DishPageQueryDTO dto){
        PageResult pageResult = dishService.pageQuery(dto);
        return Result.success(pageResult);
    }

    @GetMapping("/{id}")
    @ApiOperation("Id查询")
    public Result<DishVO> queryDishById(@PathVariable Long id){
        DishVO dishVO = dishService.queryDishById(id);
        return Result.success(dishVO);
    }

    /**
     * 菜品批量删除
     * @param ids 需要删除的ID列表
     * @return 若成功，返回success
     */
    @DeleteMapping
    @ApiOperation("批量删除")
    public Result deleteDish(@RequestParam List<Long> ids){
        log.info("菜品批量删除{}",ids);
        //清理缓存数据
        cleanAllCache();

        dishService.deleteAll(ids);
        return Result.success();
    }

    private void cleanAllCache() {
        Set keys = redisTemplate.keys("category_*");
        redisTemplate.delete(keys);
    }

    @PutMapping
    @ApiOperation("更新菜品")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        log.info("菜品修改{}",dishDTO);
        //清理缓存数据
        cleanAllCache();
        dishService.updateDish(dishDTO);
        return Result.success();
    }

    @PostMapping("/status/{status}")
    @ApiOperation("设置菜品状态")
    public Result setStatusDish(@PathVariable Integer status,Long id){
        //清理缓存数据
        cleanAllCache();
        DishDTO dishDTO = new DishDTO();
        dishDTO.setStatus(status);
        dishDTO.setId(id);
        dishService.updateDish(dishDTO);
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("分类型查询菜品")
    public Result<List> queryByCategoryId(Integer categoryId){
        List list = dishService.queryDishByCategoryId(categoryId);
        return Result.success(list);
    }
}
